import React, { useMemo, useState } from 'react';
import { Input, Select, Tree,Empty } from 'antd';
import { FolderOpenFilled, FileFilled,SearchOutlined } from '@ant-design/icons';

interface DataNode {
  title: string;
  key: string;
  icon?: React.ReactNode;
  isLeaf?: boolean;
  children?: DataNode[];
}

const initTreeData: DataNode[] = [
  {title: '0', key: '0', icon: <FolderOpenFilled style={{color: '#f7bf5c'}}/>},
  {title: '1', key: '1', icon: <FolderOpenFilled style={{color: '#f7bf5c'}}/>},
  {title: '2', key: '2', isLeaf: true, icon: <FileFilled style={{color: '#5c8ef3'}}/>},
];

const updateTreeData = (list: DataNode[], key: React.Key, children: DataNode[]): DataNode[] =>
  list.map((node) => {
    if (node.key === key) {
      return {
        ...node,
        children,
      };
    }
    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });

const DirectoryTreeSelect = (props: any) => {
  const [selectValue, setSelectValue] = useState<any>({});
  const [selectTree, setSelectTree] = useState<any>([])
  const [treeData, setTreeData] = useState(props.options || initTreeData);
  const [selectOpen, setSelectOpen] = useState(false);
  const [isEnter, setIsEnter] = useState(true);
  const [inputValue, setInputValue] = useState('')
  
  const onLoadData = ({key, children}: any) =>
    new Promise<void>((resolve) => {
      if (children) {
        resolve();
        return;
      }
      setTimeout(() => {
        setTreeData((origin) => {
            const a = Math.random() > 0.5
            const b = Math.random() > 0.5
            return updateTreeData(origin, key, [
              {
                title: `${key}-0`,
                key: `${key}-0`,
                icon: a ? <FileFilled style={{color: '#5c8ef3'}}/> : <FolderOpenFilled style={{color: '#f7bf5c'}}/>,
                isLeaf: a
              },
              {
                title: `${key}-1`,
                key: `${key}-1`,
                icon: b ? <FileFilled style={{color: '#5c8ef3'}}/> : <FolderOpenFilled style={{color: '#f7bf5c'}}/>,
                isLeaf: b
              },
            ])
          }
        )
        ;
        
        resolve();
      }, 1000);
    });
  
  const treeShowData = useMemo(() => {
    const fn = (arr: any[], val: string) => {
      return arr.map(item => {
        if (item.title.toLowerCase().indexOf(val.toLowerCase()) > -1) {
          return item
        } else if (item.children && item.children.length) {
          console.log(fn(item.children, val))
          const childrenData = fn(item.children, val)
          if (childrenData.length){
            return {...item,children:childrenData}
          }
          return null
        } else {
          return null
        }
      }).filter((a: any) => a)
    }
    if (!inputValue) {
      return treeData
    } else {
      console.log( fn(treeData, inputValue))
      return fn(treeData, inputValue);
    }
  }, [treeData, inputValue]);
  
  // const filter = (inputValue: string, path: any[]) =>
  //   path.some(
  //     (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
  //   );
  return <Select
    {...props}
    value={selectValue.title}
    open={selectOpen}
    allowClear
    onClear={() => {
      setSelectOpen(false)
      setSelectTree([])
      setSelectValue({})
    }}
    onClick={() => setSelectOpen(true)}
    onBlur={() => !isEnter && setSelectOpen(false)}
    onMouseEnter={() => setIsEnter(true)}
    onMouseLeave={() => setIsEnter(false)}
    style={{width: '100%'}}
    dropdownRender={() => <div>
      <Input addonBefore={<SearchOutlined />} placeholder={'搜索'} onChange={(e) => setInputValue(e.target.value)}/>
      {treeShowData.length?<Tree
        {...props}
        rootStyle={{minHeight:'130px'}}
        blockNode
        showIcon={true}
        loadData={onLoadData}
        treeData={treeShowData}
        selectedKeys={selectTree}
        onSelect={(selectedKeys, e) => {
          if (e.node.isLeaf && selectTree[0] !== selectedKeys[0]) {
            setSelectTree(selectedKeys)
            setSelectValue(e.node)
            setTimeout(()=>setSelectOpen(false),0)
            
          }
          
          
        }}
      />:<Empty />}
    </div>}
    onChange={() => {
    }}
  />
};

export default DirectoryTreeSelect;